<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_使用Promise+XHR_获取省份列表</title>
</head>

<body>
  <p class="my-p"></p>
  <script>
    /**
     * 目标：使用Promise管理XHR请求省份列表
     *  1. 创建Promise对象
     *  2. 执行XHR异步代码，获取省份列表
     *  3. 关联成功或失败函数，做后续处理
    */
    function myAxios(config) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        //?
        xhr.open(config.method || 'GET', config.url)
        xhr.addEventListener('loadend', () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(JSON.parse(xhr.response));

          } else {
            reject(new Error(xhr.response));
          }
        })
        xhr.send()
      })
    }
    myAxios({
      url: 'https://hmajax.itheima.net/api/province',
    }).then(result => {
      console.log(result);
      document.querySelector('.my-p').innerHTML = result.list.join('<br>')
    }).catch(error => {
      console.dir(error.message);
      document.querySelector('.my-p').innerHTML = error.message
    })
  </script>
</body>

</html>